<?php

namespace Jammiest\SwigeCore\Servers;

use Jammiest\SwigeCore\Tools\Config;
use Jammiest\SwigeCore\Handlers\EventHandler;
use Psr\Container\ContainerInterface;

class Http extends Server
{

    public static function getInstance(array $config,ContainerInterface $container): \Swoole\Http\Server
    {
        if (!self::$server) {
            /**
             * @var EventHandler
             */
            $eventHandler = new class($container) extends EventHandler {};
            $config = Config::get('server');
            $server = new \Swoole\Http\Server($config['host'], $config['port']);
            $server->set($config['settings']);

            $server->on('request', function ($request, $response) use ($eventHandler) {
                $eventHandler->onRequest($request, $response);
            });

            if (isset($config['settings']['task_worker_num'])) {
                //处理异步任务(此回调函数在task进程中执行)。
                $server->on('Task', function ($serv, $task_id, $reactor_id, $data) use ($eventHandler) {
                    $eventHandler->onTask($serv, $task_id, $reactor_id, $data);
                });

                //处理异步任务的结果(此回调函数在worker进程中执行)。
                $server->on('Finish', function ($serv, $task_id, $data) use ($eventHandler) {
                    $eventHandler->onFinish($serv, $task_id, $data);
                });
            }
            self::$server = $server;
        }

        return self::$server;
    }
}
